-- 帝王蟹辅助，该功能最好开启延迟补偿

local function EquipInHand(equipments)
    local hands = GetEquippedItemFrom(GLOBAL.EQUIPSLOTS.HANDS)
    if hands and equipments == hands.prefab then
    else
        hands = GetItemFromAll(equipments)
        if hands then
            SendActionAndFn(GLOBAL.BufferedAction(GLOBAL.ThePlayer, nil, GLOBAL.ACTIONS.EQUIP, hands), function()
                GLOBAL.SendRPCToServer(GLOBAL.RPC.ControllerUseItemOnSelfFromInvTile, GLOBAL.ACTIONS.EQUIP.code, hands)
            end)
        end
    end
    return hands
end

local function Init()
    local PlayerController = GLOBAL.ThePlayer and GLOBAL.ThePlayer.components.playercontroller

    if not PlayerController then
        return
    end

    local OldGetAttackTarget = PlayerController.GetAttackTarget
    function PlayerController:GetAttackTarget(...)
        local force_target = OldGetAttackTarget(self, ...)
        if force_target then
            if force_target.prefab == "crabking" and force_target.AnimState then
                -- 帝王蟹准备放水柱时切冰杖
                local find_claw = PlayerFindEnt("crabking_claw", 10, nil, nil, {"clamp","clamping"}, nil)

                local have = GetEquippedItemFrom(GLOBAL.EQUIPSLOTS.HANDS)
                if c_anim({"cast_purple_pre", "cast_purple_loop"}, force_target) then
                    EquipInHand("icestaff")
                elseif find_claw then
                    TIP("切火腿打蟹钳")
                    EquipInHand("hambat")
                    return find_claw
                elseif c_anim("frozen", force_target) then
                    if find_claw then
                        force_target = find_claw
                    end
                    EquipInHand("hambat")
                elseif have and have.prefab == "staff_tornado" then
                    EquipInHand("hambat")
                end
            elseif force_target.prefab == "crabking_claw" then
                EquipInHand("hambat")
            end
        end
        return force_target
    end

    local OldOnRightClick = PlayerController.OnRightClick
    function PlayerController:OnRightClick(down, ...)
        if not down then
            return OldOnRightClick(self, down)
        end

        local ent = GLOBAL.TheInput:GetWorldEntityUnderMouse()
        if ent and ent.prefab == "crabking" then
            local have = EquipInHand("staff_tornado")
            local ent_pos = ent:GetPosition()
            SendActionAndFn(GLOBAL.BufferedAction(GLOBAL.ThePlayer, ent, GLOBAL.ACTIONS.CASTSPELL, have), function()
                GLOBAL.SendRPCToServer(GLOBAL.RPC.RightClick, GLOBAL.ACTIONS.CASTSPELL.code, ent_pos.x, ent_pos.z, ent, nil, false)
            end)
        end
        
        return OldOnRightClick(self, down, ...)
    end
end


local function OnWorldPostInit(inst)
    inst:ListenForEvent("playeractivated", Init, GLOBAL.TheWorld)
end
AddPrefabPostInit("world", OnWorldPostInit)